package com.atguigu.tingshu.album.receiver;


import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class AlbumReceiver {

    @Autowired
    private AlbumInfoService albumInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 更新声音专辑播放量
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void trackStatUpdate(ConsumerRecord<String,String> record){

        String value = record.value();

        if (!StringUtils.isEmpty(value)) {
            //将sting转成对象
            TrackStatMqVo trackStatMqVo = JSON.parseObject(value, TrackStatMqVo.class);

            //业务编号 去重使用
            String businessNo = trackStatMqVo.getBusinessNo();

            //第一次执行result=true
            Boolean result = redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 1, TimeUnit.DAYS);

            if (result) {
                try {
                    //更新播放量
                    albumInfoService.trackStatUpdate(trackStatMqVo);
                } catch (Exception e) {
                    //如果有异常删除原有的key
                    redisTemplate.delete(businessNo);
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
